<?php
/**
 * 特殊独立奖池用户详情
 */
namespace App\Models\MainDB;

use App\Services\Tools\HelperService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class IndependentPoolUserDetail extends Model{

    protected $table = 'ln_independent_pool_user_detail';     //数据库内完整表名

    protected $primaryKey = 'id';    //主键名

    protected $fillable = [
        'id',      //主键ID
        'user_id',         //用户id
        'gift_id',
        'number',
        'type',
    ];

    public $timestamps = false;

    //获取列表
    public function getUserIndependentPoolList($user_id) {
        $list = $this->from('ln_independent_pool_user_detail as a')
            ->select('a.id', 'a.gift_id', 'a.number', 'a.type', 'b.name as gift_name', 'b.price', 'b.picture', 'b.special','a.critical_times')
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->where(['a.user_id' => $user_id])
            ->orderBy('b.price', 'desc')
            ->get()->toArray();
        foreach ($list as &$value) {
            $value['quality'] = HelperService::giftRank($value['price']);
        }

        return $list;
    }

    //获取剩余次数
    public function getUserIndependentPoolCount($user_id)
    {
        $total = $this->where(['user_id' => $user_id])->sum('number');
        return $total ?: 0;
    }

    //获取剩余总金额
    public function getUserIndependentPoolTotal($user_id)
    {
        $total = $this->from('ln_independent_pool_user_detail as a')
            ->where(['a.user_id' => $user_id])
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->sum(DB::raw('a.number*b.price'));
        return $total ?: 0;
    }

}